package data.admin;

import dao.SQLiteConnection;
import gui.admin.BorrowWin;
import javax.swing.*;
import java.sql.*;
import static utils.Time.getLimitTime;
import static utils.Time.getNowTime;

public class Borrow extends BorrowWin {

    String ISBN;
    String rid;
    int number=0;
    boolean b1=false;
    boolean b2 =false;
    boolean b3=false;

    public Borrow(String ISBN){
        this.ISBN=ISBN;
        //自动输入ISBN码
        getT1().setText(ISBN);
        //借出按钮
        getB1().addActionListener(e->{
            this.ISBN=getT1().getText(); // ISBN
            this.rid=getT2().getText(); // rid
            // 空判断
            if(this.ISBN.isEmpty()){
                JOptionPane.showMessageDialog(this,"请输入ISBN码！");
            }
            else if(this.rid.isEmpty()){
                JOptionPane.showMessageDialog(this,"请输入读者账号！");
            }
            else{
                check();
                BorrowBook();
            }
        });
    }
    // ISBN, rid信息验证
    public void check(){
        SQLiteConnection connection=new SQLiteConnection();
        connection.Connect_SQLite();
        Connection conn=connection.getConnection();
        PreparedStatement stmt;
        ResultSet rs;
        // ISBN查询
        try {
            String sql1="select number from Book where ISBN='"+this.ISBN+"'";
            stmt=conn.prepareStatement(sql1);
            rs=stmt.executeQuery();
            //ISBN有效
            if (rs.next()) {
                number = rs.getInt("number"); // 获取查询结果集中number列的值
                this.b1=true;
            }
            // ISBN无效
            else {
                System.out.println("ISBN无效:"+this.ISBN);
                JOptionPane.showMessageDialog(this,"请输入正确的ISBN码！");
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
        // 读者验证
        try{
            String sql2="select rid from Reader where rid='"+this.rid+"'";
            stmt=conn.prepareStatement(sql2);
            rs=stmt.executeQuery();
            if (rs.next()) {
                System.out.println("读者验证通过");
                this.b2=true;
            } else {
                System.out.println("读者账号无效:"+this.rid);
                JOptionPane.showMessageDialog(this,"请输入正确的读者账号！");
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
        // 读者验证
        try{
            // 是否有未缴纳罚金
            String sql3="select * from Reader " +
                    "where state=1 and rid='"+rid+"'";
            stmt=conn.prepareStatement(sql3);
            rs=stmt.executeQuery();
            if(rs.next()){
                JOptionPane.showMessageDialog(this,"读者有未缴纳罚金！");
            }
            else{
                sql3="select COUNT(*) from Borrow " +
                        "inner join Record on Record.bid=Borrow.bid " +
                        "where rid='"+rid+"' and rtime is null";
                stmt=conn.prepareStatement(sql3);
                rs=stmt.executeQuery();
                if (rs.next()) {
                    int count=rs.getInt(1);
                    // 借书4本
                    if(count>=4){
                        JOptionPane.showMessageDialog(this,"读者借书达到上限！");
                    }
                    // 小于4本
                    else{
                        this.b3=true;
                    }
                }
            }

        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }finally {
            connection.closeConnection();
        }
    }

    // 借书函数
    public void BorrowBook(){
        if(this.b1 && this.b2&&this.b3){
            if(this.number==0){
                JOptionPane.showMessageDialog(this,"该图书馆藏为0！");
            }else{
                // 向Borrow表插入借阅信息
                SQLiteConnection connection=new SQLiteConnection();
                connection.Connect_SQLite();
                Connection conn=connection.getConnection();
                PreparedStatement stmt;
                try{
                    int rowsInserted;
                    String btime = getNowTime();
                    String ltime = getLimitTime();
                    //向Borrow表插入记录
                    String sql2="insert into Borrow(btime,ltime) " +
                            "values('"+btime+"','"+ltime+"')";
                    stmt=conn.prepareStatement(sql2);
                    rowsInserted=stmt.executeUpdate();
                    if (rowsInserted > 0) {
                        System.out.println("借出时间："+btime);
                        this.dispose();
                    } else {
                        System.out.println("插入失败");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this,"借出失败！");
                    throw new RuntimeException(ex);
                }
                // 向Record表插入借阅记录
                try{
                    int rowsInserted;
                    String sql3="insert into Record(ISBN,rid) values('"+this.ISBN+"','"+this.rid+"')";
                    System.out.println(sql3);
                    stmt=conn.prepareStatement(sql3);
                    rowsInserted=stmt.executeUpdate();
                    if (rowsInserted > 0) {
                        System.out.println(this.rid + "借出" + this.ISBN);
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                // 更新Book表的数据（馆藏数量-1）
                try {
                    String sql="UPDATE Book SET number = number - 1 WHERE ISBN='"+this.ISBN+"'";
                    int rowsInserted;
                    stmt=conn.prepareStatement(sql);
                    rowsInserted=stmt.executeUpdate();
                    if (rowsInserted > 0) {
                        System.out.println(this.rid + "借出" + this.ISBN);
                        JOptionPane.showMessageDialog(this, "成功借出");
                        this.dispose();
                    }
                }catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                connection.closeConnection();
            }
        }
    }

}
